package com.red.wood.module.eval.web;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.red.wood.common.util.CommonUtils;
import com.red.wood.common.util.IMap;
import com.red.wood.module.eval.model.SingleTask;
import com.red.wood.module.eval.model.TaskAudit;
import com.red.wood.module.eval.service.EvalProjectService;
import com.red.wood.module.eval.service.SingleTaskService;
import com.red.wood.module.eval.service.TaskAuditService;
import com.red.wood.module.eval.service.TaskFlowService;
import com.red.wood.module.evalMol.service.MolService;

@Controller
@RequestMapping("/evalProject")
public class EvalProjectController {
	
	private static final Log log = LogFactory.getLog(EvalProjectController.class);
	@Autowired
	private EvalProjectService service;
	@Autowired
	private TaskAuditService taskAuditService;
	@Autowired
	private SingleTaskService singleTaskService;
	@Autowired
	private TaskFlowService taskFlowService;
	@Autowired
	private MolService molService;
	
	/**
	 * 评测项目
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping
	public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
		String htmlView = "evalProjectNotInter";
		String backViewType = CommonUtils.valueOf(request.getParameter("backViewType")); // 返回界面标识 1-企业侧 2-管局侧
		String type = CommonUtils.valueOf(request.getParameter("type")); // 表单类型：1-idc业务评测(不含互联网资源协作) 2-idc业务评测(仅限互联网资源协作) 3-ISP业务评测 4-CDN业务评测
//		if(StringUtils.isNotBlank(backViewType) && Integer.valueOf(backViewType) == 2){ // 管局
			if(Integer.valueOf(type) ==  SingleTask.EVAL_SINGLETASK_TYPE_ONLYINTER){ // idc业务评测(仅限互联网资源协作)
				htmlView = "evalProjectOnlyInter";
			} else if(Integer.valueOf(type) ==  SingleTask.EVAL_SINGLETASK_TYPE_ISP) { // ISP业务评测 
				htmlView = "evalProjectIsp";
			} else if(Integer.valueOf(type) ==  SingleTask.EVAL_SINGLETASK_TYPE_CDN) { // CDN业务评测
				htmlView = "evalProjectCdn";
			} else {
				htmlView = "evalProjectNotInter";
			}
//		}
		ModelAndView mv = new ModelAndView(htmlView);
		String singleTaskId = CommonUtils.valueOf(request.getParameter("singleTaskId"));
		mv.addObject("singleTaskId", singleTaskId); 
		mv.addObject("backViewType", backViewType); 
		mv.addObject("type", type);
		mv.addObject("statue", CommonUtils.valueOf(request.getParameter("statue"))); 
		Map<String, Object> map = singleTaskService.getById(singleTaskId);
		mv.addObject("userId",  map == null?"1":map.get("userId").toString());
		return mv;
	}
	
	
	/**
	 * 获取审核信息
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "getProject", method = RequestMethod.POST)
	@ResponseBody
	public String getProject(String singleTaskId, String businessType){
		JSONObject json = new JSONObject();
		try{
			json.put("flag", true);
			json.put("projectList", service.getData(singleTaskId));
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	private void updateState(HttpServletRequest request){
		// 更新工单状态
		String statue = CommonUtils.valueOf(request.getParameter("statue"));
		String singleTaskId = CommonUtils.valueOf(request.getParameter("singleTaskId"));
		String type = CommonUtils.valueOf(request.getParameter("type"));
		
		if(StringUtils.isNotBlank(statue)){ // 保存
			// 更新工单状态 和 研究院审核状态
			IMap iMap = new IMap();
			iMap.put("statue", statue);
			iMap.put("singleTaskId", singleTaskId);
			iMap.put("updateTime", new Date());
			if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_BACK || Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_RETURNPATCH){
				Map<String,Object> map = taskAuditService.getBySingleTaskId(singleTaskId);
				if(map != null){
					iMap.put("returnNum", Integer.valueOf(map.get("returnNum").toString())+1);
				}
			} 
			taskAuditService.update(iMap);
			iMap.put("singleTaskId", null); // 不是库中字段，设为空
			iMap.put("returnNum", null); // 不是库中字段，设为空
			iMap.put("updateTime", null); // 不是库中字段，设为空
			iMap.put("id", singleTaskId);
			if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_ADOPT){ //评测通过
				iMap.put("statue", SingleTask.EVAL_SINGLETASK_STATUE_ADOPT);
			} else if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_NOTADOPT){ // 评测不通过
				iMap.put("statue", SingleTask.EVAL_SINGLETASK_STATUE_NOTADOPT);
			} else if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_RETURNPATCH){ //退回补正
				iMap.put("statue", SingleTask.EVAL_SINGLETASK_STATUE_RETURN);
			} else if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_HANLE){ //评测中
				iMap.put("statue", SingleTask.EVAL_SINGLETASK_STATUE_JUDGING);
			} else if(Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_NOTAUDIT 
					|| Integer.valueOf(statue) == TaskAudit.EVAL_TASTAUDIT_STATUE_BACK ){ // 撤销核实 或退回修改
				iMap.put("statue", SingleTask.EVAL_SINGLETASK_STATUE_RETURNUPDATE);
			} 
			singleTaskService.update(iMap);
			
			// 增加流程记录
			Map<String, Object> flowMap = new HashMap<>();
			flowMap.put("singleTaskId", singleTaskId);
			Map<String,Object> userMap = singleTaskService.getUserById(singleTaskId);
			flowMap.put("userName", userMap == null?"张三":userMap.get("UserName").toString());
			flowMap.put("handleTime", new Date());
			String btnName = CommonUtils.valueOf(request.getParameter("btnName"));
			flowMap.put("statue", btnName);
			flowMap.put("reason", CommonUtils.valueOf(request.getParameter("reason")));
			taskFlowService.add(flowMap);
			
			//评测通过、评测不通过入历史工单
			if(StringUtils.equals(statue, "5") || StringUtils.equals(statue, "6")) {
				//查找对应工单
				Map<String, Object> map = taskFlowService.getHistoryWorkOrderInfo(singleTaskId);
				String formNumber = CommonUtils.valueOf(map.get("form_number"));
				//判断表单编号在历史工单中是否存在
				boolean exists = taskFlowService.getHistoryWorkOrderByFormNumber(formNumber);
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				map.put("daytime", sdf.format(new Date()));
				if(!exists) {
					taskFlowService.insertHistoryWorkOrder(map);
				}else {
					String queryConf = " where form_number='"+formNumber+"'";
					taskFlowService.updateHistoryWorkOrder(map, queryConf);
				}
				
				//通过不通过报告数据入库
				molService.saveMol(Integer.valueOf(statue), Integer.valueOf(type), singleTaskId);
			}
			
		}
	}
	
	@RequestMapping(value = "operation", method = RequestMethod.POST)
	@ResponseBody
	public String operation(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{
			updateState(request);
			json.put("flag", true);
		} catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	/**
	 * 通过不通过
	 * @param entity
	 * @param request
	 */
	@RequestMapping(value = "handle", method = RequestMethod.POST)
	@ResponseBody
	public String handle(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{
			IMap iMap = new IMap(request);
			String singleTaskId = CommonUtils.valueOf(request.getParameter("singleTaskId"));
			String realIndex = CommonUtils.valueOf(request.getParameter("realIndex"));
			String type = CommonUtils.valueOf(request.getParameter("type"));
			if(StringUtils.isNotBlank(singleTaskId)){
				int count = service.getBySingleTaskIdAndIndex(singleTaskId, realIndex, type);
				if(count > 0){
					service.update(iMap);
				} else {
					service.add(iMap);
				}
			}
			json.put("flag", true);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	/**
	 * 增加不通过原因
	 * @param entity
	 * @param request
	 */
	@RequestMapping(value = "upReason", method = RequestMethod.POST)
	@ResponseBody
	public String upReason(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{
			String singleTaskId = CommonUtils.valueOf(request.getParameter("singleTaskId"));
			String realIndex = CommonUtils.valueOf(request.getParameter("realIndex"));
			String type = CommonUtils.valueOf(request.getParameter("type"));
			if(StringUtils.isNotBlank(singleTaskId)){
				int count = service.getBySingleTaskIdAndIndex(singleTaskId, realIndex, type);
				if(count > 0){
					IMap iMap = new IMap(request);
					service.update(iMap);
				} 
			}
			json.put("flag", true);
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
	
	/**
	 * 校验评测项是否全部评测通过
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "getEvalProjectResult", method = RequestMethod.POST)
	@ResponseBody
	public String getEvalProjectResult(HttpServletRequest request){
		JSONObject json = new JSONObject();
		try{
			String singleTaskId = CommonUtils.valueOf(request.getParameter("singleTaskId"));
			json.put("flag", true);
			json.put("count",service.getEvalProjectResult(singleTaskId));
		} catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
			json.put("flag",false);
		}
		return json.toString();
	}
}
